//
//  UIBodyProfileViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/19/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "UIBodyProfileViewCtrl.h"
#import "AppDelegate.h"
#import "UIView+Extension.h"
//debug
#import "H_Rate.h"
#import "H_RateItem.h"
//debug

#define _fRowHgt 30 //37
#define _nRecdCound 21

@interface LoginBodyInfo ()

@end

@implementation LoginBodyInfo {
  NSInteger _nBodyId;
  NSString* _sTagId;
  NSString* _sUserId;
  
  BOOL _bMgr;
  NSInteger _nClubAdmin;
  
  NSString* _sEmail;
  NSString* _sFirst;
  NSString* _sLast;
  
  Byte _nGender;
  Byte _nYearAge;
    
  float _fBodyWgt;
  float _fBodyHgt;
  Byte _nWgtUn;
  Byte _nHgtUn;
    
  short _nHgtCm;
  Byte _nActLvl;
  NSDate* _dtBorn;
    
  float _fGoalWgt;
  int _nGoalStep;
  float _fGoalDist;
  Byte _nDistUnit;
  
  int _nMaxBpm;
  int _nMinBpm;
  
  float _fChestSize;
  float _fWaistLine;
  
  float _fCaloriesDay;
  short _nGymVisitWeek;
  
  NSString* _sStoreLoc;
  NSString* _sProgram;
  NSString* _sTerms;
  
  Byte _nSvrIpIdx;
    
  NSDateFormatter* _dtFmt;
}
@synthesize m_nBodyId = _nBodyId;
@synthesize m_sTagId = _sTagId;
@synthesize m_sUserId = _sUserId;
@synthesize dtBorn = _dtBorn;

@synthesize nGoalStep = _nGoalStep;
@synthesize fGoalDist = _fGoalDist;
@synthesize nDistUnit = _nDistUnit;

 - (id) init
{
  self = [super init];
  _nBodyId = 0;
  _sTagId = @"";
  _sUserId = @"";
  
  _bMgr = NO;
  _nClubAdmin = -1;
  
  _sEmail = @"";
  _sFirst = @"";
  _sLast = @"";
  
  _fBodyWgt = 0.0f;
  _fBodyHgt = 0.0f;
  _nHgtCm = 0;
  
  _nGoalStep = 0.0f;
  _nGoalStep = 0;
  _fGoalDist = 0.0f;
  
  _fChestSize = 0.0f;
  _fWaistLine = 0.0f;
  
  _nMaxBpm = 0;
    
  _dtFmt = [[NSDateFormatter alloc]init];
  _sStoreLoc = @"";
  
  /*NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  NSInteger nSvrIpIdx = [userSetting integerForKey:kReg_BodySvrIdx];
  if(nSvrIpIdx > 0) {
    _nSvrIpIdx = (Byte)nSvrIpIdx;
  }
  else {
    if([AppDelegate isLanguageChines])
      _nSvrIpIdx = 1;
    else
      _nSvrIpIdx = 0;
  }*/
  
  if([AppDelegate isLanguageChines]) {
    _nSvrIpIdx = 1;
    [_dtFmt setDateFormat:@"yyyy-MM"];
  }
  else {
    _nSvrIpIdx = 0;
    [_dtFmt setDateFormat:@"MM/yyyy"];
  }
  
  _nDistUnit = 2;
  
  return self;
}

-(NSString*) getBornDate
{
  if(_dtBorn != nil) {
    //NSString* sInitDtFmt = _dtFmt.dateFormat;
    return [_dtFmt stringFromDate:_dtBorn];
  }
  else {
    return @"";
  }
}

@end

@interface UIBodyProfileViewCtrl ()

@end

@implementation UIBodyProfileViewCtrl {
  NSString* _sBodyInfoTitle[_nRecdCound];
  NSString* _sBodyInfoValue[_nRecdCound];
  
  
  UITableView* _tabProf;
  UITextField* _txtEditBox;
  UISegmentedControl* _scCtrlBox;
  UITextField* _txtHgtIn;
  UILabel* _lblUnit;
  short _nUpdIdx;
  NSIndexPath* _lastIdxPath;
  
  UIButton* _btnUpdate;
  UIButton* _btnCancel;
  
  CGPoint _tabProfPos;
  
  //debug & test
  UIButton* _btnClearData;
  UIButton* _btnLogout;
  UILabel* _lblAppVer;
    
  //debug
  NSMutableArray* _pHrateItem;
  //denbug
  
  NSString* _sDevId;
  NSTimer* _tagIdTimer;
}

- (void)viewDidLoad {
  [super viewDidLoad];
    
  // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    CGRect frame = [[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
   BOOL bIpad = H > 1000;
    
    CGFloat yPos = bIpad? 65: 2;
    //table for profile data
  _tabProf = [[UITableView alloc] initWithFrame:CGRectMake(0, yPos, W, H - (bIpad?120:40))];
  _tabProf.backgroundColor = [UIColor whiteColor];//[UIColor colorWithWhite:0.25 alpha:0.5];
  _tabProf.separatorColor = [UIColor grayColor];
  _tabProf.delegate = self;
  _tabProf.dataSource = self;
  _tabProf.sectionHeaderHeight = 30;
  _tabProf.sectionFooterHeight = 20;
  [self.view addSubview:_tabProf] ;
  //[_tabProf setEditing:YES];
  
  _tabProfPos = CGPointMake(W/2, (yPos + H - 40)/2);
  
  _txtEditBox = [[UITextField alloc] init];
  _txtEditBox.adjustsFontSizeToFitWidth = NO;
  _txtEditBox.textColor = [UIColor blueColor];
  _txtEditBox.backgroundColor = [UIColor whiteColor];
  _txtEditBox.autocorrectionType = UITextAutocorrectionTypeNo;
  _txtEditBox.autocapitalizationType = UITextAutocapitalizationTypeWords;
  _txtEditBox.textAlignment = NSTextAlignmentLeft;
  _txtEditBox.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  _txtEditBox.returnKeyType = UIReturnKeyDone;
  _txtEditBox.clearButtonMode = UITextFieldViewModeNever;
  _txtEditBox.delegate = self;
  
   _scCtrlBox = [[UISegmentedControl alloc] initWithItems:@[@"Female", @"Male"]];
   //[_scCtrlBox addTarget:self action:@selector(onUnitChged:) forControlEvents:UIControlEventValueChanged];
  
  _txtHgtIn = [[UITextField alloc] init];
  _txtHgtIn.adjustsFontSizeToFitWidth = NO;
  _txtHgtIn.textColor = [UIColor blueColor];
  _txtHgtIn.backgroundColor = [UIColor whiteColor];
  _txtHgtIn.autocorrectionType = UITextAutocorrectionTypeNo;
  _txtHgtIn.autocapitalizationType = UITextAutocapitalizationTypeWords;
  _txtHgtIn.textAlignment = NSTextAlignmentLeft;
  _txtHgtIn.keyboardType = UIKeyboardTypeNumberPad;
  _txtHgtIn.returnKeyType = UIReturnKeyDone;
  _txtHgtIn.clearButtonMode = UITextFieldViewModeNever;
  _txtHgtIn.delegate = self;
  
  _lblUnit = [[UILabel alloc] init];
  _lblUnit.textColor = [UIColor grayColor];
  _lblUnit.font = [UIFont systemFontOfSize:15.0];
  _lblUnit.backgroundColor = [UIColor clearColor];
  _lblUnit.textAlignment = NSTextAlignmentLeft;
  
  
  UIImage* iBtn = [UIImage imageNamed: @"ic-update.png"];
  _btnUpdate = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [_btnUpdate setBackgroundImage:iBtn forState:UIControlStateNormal];
  //_btnUpdate = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
  [_btnUpdate addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
  
  iBtn = [UIImage imageNamed: @"ic-cancel.png"];
  _btnCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [_btnCancel setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnCancel addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
  
  
  //_bbiUpdate = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:_bbiUpdate action:@selector(tapImgBtnView:)];
  //_bbiCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:_bbiUpdate action:@selector(tapImgBtnView:)];
  
  
  //debug clear button
  
  //app version
  NSString* sAppVer  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
  yPos = H - 40;
  CGFloat xPos = 20;
  _lblAppVer = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos+5, bIpad?200:150, 36)];
  _lblAppVer.textColor = [UIColor blackColor];
  _lblAppVer.text = [NSString stringWithFormat:@"Ver: %@", sAppVer];//@"Ver: 1.2.1C";
  _lblAppVer.textAlignment = NSTextAlignmentCenter;
  [self.view addSubview:_lblAppVer];
  _lblAppVer.hidden = YES;
  
  xPos = bIpad?(W - 200)/2-10 : W /22;
  /*_btnClearData = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnClearData.frame = CGRectMake(xPos, yPos,  bIpad?200:W/3, 28);
  _btnClearData.backgroundColor = [UIColor lightGrayColor];
  [_btnClearData setTitle:@"Clear Data" forState:UIControlStateNormal];
  [_btnClearData setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  _btnClearData.layer.masksToBounds = YES;
  _btnClearData.layer.cornerRadius = 4;
  [_btnClearData addTarget:self action:@selector(onUserLogout:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnClearData];*/
  //_btnClearData.hidden = YES;
  
  _btnLogout = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnLogout.frame = CGRectMake(15, H - (H / 16.7) - 20, self.view.frame.size.width - 30, H / 16.7);
    _btnLogout.backgroundColor =  [UIColor colorWithRed:0.84 green:0.13 blue:0.46 alpha:1.00];
  [_btnLogout setTitle:NSLocalizedString(@"Logout", nil) forState:UIControlStateNormal];
  [_btnLogout setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  _btnLogout.layer.masksToBounds = YES;
  _btnLogout.layer.cornerRadius = 4;
  [_btnLogout addTarget:self action:@selector(onUserLogout:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnLogout];
  //_btnLogout.hidden = YES;

  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    _nUpdIdx = -1;
    [self getWgtGoalData:pApp];
    [self setBodyInfo];
    
    _sDevId = nil;
    _tagIdTimer = nil;
    
    UIImage* iNav = [UIImage imageNamed:@"profileicon"];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:iNav];
    imgView.frame = CGRectMake(0, 0, 27, 27);
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    self.navigationItem.titleView = imgView;
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
    [btnBack addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = btniBack;
}

-(void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) viewWillDisappear:(BOOL)animated {
  if(_tagIdTimer != nil) {
    [_tagIdTimer invalidate];
    _tagIdTimer = nil;
  }
}

- (void) getWgtGoalData:(AppDelegate*) pApp
{
  [pApp getUserGoalData: YES];
}

- (void) setBodyInfo
{
    _sBodyInfoTitle[0] = NSLocalizedString(@"Name", nil);
    _sBodyInfoTitle[1] = NSLocalizedString(@"Last Name", nil);
    _sBodyInfoTitle[2] = NSLocalizedString(@"Email", nil);
    _sBodyInfoTitle[3] = NSLocalizedString(@"TagID", nil);
    _sBodyInfoTitle[4] = NSLocalizedString(@"Date of Birth", nil);
    _sBodyInfoTitle[5] = NSLocalizedString(@"Gender", nil);
    _sBodyInfoTitle[6] = NSLocalizedString(@"Start Weight", nil);
    _sBodyInfoTitle[7] = NSLocalizedString(@"Body Height", nil);
    _sBodyInfoTitle[8] = NSLocalizedString(@"Activity Level", nil);
    _sBodyInfoTitle[9] = NSLocalizedString(@"Goal Weight", nil);
    _sBodyInfoTitle[10] = NSLocalizedString(@"Goal Steps", nil);
    _sBodyInfoTitle[11] = NSLocalizedString(@"Goal Distance", nil);
    _sBodyInfoTitle[12] = NSLocalizedString(@"Max Heart Rate", nil);
    
    _sBodyInfoTitle[13] = NSLocalizedString(@"Chest Size", nil);
    _sBodyInfoTitle[14] = NSLocalizedString(@"Waist Line", nil);
    
    _sBodyInfoTitle[15] = NSLocalizedString(@"Calories/day", nil);
    _sBodyInfoTitle[16] = NSLocalizedString(@"Gym Visit/week", nil);
    
    _sBodyInfoTitle[17] = NSLocalizedString(@"Club", nil);
    _sBodyInfoTitle[18] = NSLocalizedString(@"Challenges", nil);
    _sBodyInfoTitle[19] = NSLocalizedString(@"Team", nil);
    _sBodyInfoTitle[20] = NSLocalizedString(@"Svr Address", nil);
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
  if(bodyInfo == nil)
    return;
  
  _sBodyInfoValue[0] = bodyInfo.sFirst;
  _sBodyInfoValue[1] = bodyInfo.sLast;
  _sBodyInfoValue[2] = bodyInfo.sEmail;
  _sBodyInfoValue[3] = bodyInfo.m_sTagId;
  _sBodyInfoValue[4] = bodyInfo.getBornDate;
  _sBodyInfoValue[5] = [NSString stringWithFormat:@"%@", (bodyInfo.nGender == 1)?NSLocalizedString(@"Male", nil):NSLocalizedString(@"Female", nil)];
  short nUnit = bodyInfo.nWgtUn;
  NSString* sWgtUnit = (nUnit==2)?@"kg": @"kg";
  _sBodyInfoValue[6] = [NSString stringWithFormat:@"%.1f %@", bodyInfo.fBodyWgt, sWgtUnit];
  
  //float fBodyHgt = bodyInfo.fBodyHgt;
  if(bodyInfo.nHgtUn == 2) {
    float fInch = (bodyInfo.fBodyHgt - (Byte)bodyInfo.fBodyHgt) * 12.0;
    _sBodyInfoValue[7] = [NSString stringWithFormat:@"%ift %iin", (short)bodyInfo.fBodyHgt, (short)(fInch +0.5)];
  }
  else {
    _sBodyInfoValue[7] = [NSString stringWithFormat:@"%.0f cm", bodyInfo.fBodyHgt*100];
  }
  
  if(bodyInfo.nActLvl == 1)
    _sBodyInfoValue[8] = @"Active";
  else if(bodyInfo.nActLvl == 2)
    _sBodyInfoValue[8] = @"Very Active";
  else
    _sBodyInfoValue[8] = @"Not Active";

  //test start
  //float fGoalWgt = bodyInfo.fGoalWgt;
  //int nStep = bodyInfo.nGoalStep;
  //NSString* sGoalWgt = [NSString stringWithFormat:@"%.1f %@", bodyInfo.fGoalWgt, sWgtUnit];
  //test end
  _sBodyInfoValue[9] = [NSString stringWithFormat:@"%.1f %@", bodyInfo.fGoalWgt, sWgtUnit];
  _sBodyInfoValue[10] = [NSString stringWithFormat:@"%d", bodyInfo.nGoalStep];
  
  if(bodyInfo.fGoalDist > 5)
    _sBodyInfoValue[11] = [NSString stringWithFormat:@"%.1f", bodyInfo.fGoalDist];
  else if(bodyInfo.fGoalDist > 1 )
    _sBodyInfoValue[11] = [NSString stringWithFormat:@"%.2f", bodyInfo.fGoalDist];
  else
    _sBodyInfoValue[11] = [NSString stringWithFormat:@"%.3f", bodyInfo.fGoalDist];
  
  //if(bodyInfo.nGoalBpm > 0)
  _sBodyInfoValue[12] = [NSString stringWithFormat:@"%i", bodyInfo.nMaxBpm];
  
  if(bodyInfo.fChestSize > 0)
    _sBodyInfoValue[13] = [NSString stringWithFormat:@"%0.1f %@", bodyInfo.fChestSize, ((bodyInfo.nHgtUn==2)?@"in":@"cm")];
  if(bodyInfo.fWaistLine > 0)
    _sBodyInfoValue[14] = [NSString stringWithFormat:@"%0.1f %@", bodyInfo.fWaistLine, ((bodyInfo.nHgtUn==2)?@"in":@"cm")];
  
  _sBodyInfoValue[15] =  [NSString stringWithFormat:@"%.1f", bodyInfo.fCaloriesDay];
  _sBodyInfoValue[16] =  [NSString stringWithFormat:@"%i", bodyInfo.nGymVisitWeek];
  
  
  _sBodyInfoValue[17] =  bodyInfo.sStoreLoc;
  _sBodyInfoValue[18] =  bodyInfo.sProgram;
  _sBodyInfoValue[19] =  bodyInfo.sTerms;
  
  _sBodyInfoValue[20] = (bodyInfo.nSvrIpIdx==0)?@"Americas":@"Internationl";
}

- (void) viewWillAppear:(BOOL)animated
{
  self.navigationItem.hidesBackButton = NO;
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  //_lblMsg.text = @"No enough memory!";
  AudioServicesPlaySystemSound(1112);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma -
#pragma table data view detegate
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;//indexPath.row == _nTableEditRow;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _fRowHgt;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {
  return 4;
}

//- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//  if(section == 0)
//    return @"Profile";
//  else if(section == 1)
//    return @"Weight & Measurement";
//  else if(section == 2)
//    return @"Goals";
//  else
//    return @"More";
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //创建一个用于返回效果的UIView，用来承接文字或图片
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 35.0)] ;
    customView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    //自定义文字效果
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    headerLabel.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    //字体不透明
    headerLabel.opaque =NO;
    headerLabel.textColor = [UIColor blackColor];
    //
    headerLabel.highlightedTextColor = [UIColor blackColor];
    //字体效果
    headerLabel.font = Regular(14);
    //设置label格式
    headerLabel.frame = CGRectMake(10.0, 0.0, 320.0, 35.0);
    
    if (section == 0) {
        headerLabel.text =  NSLocalizedString(@"Profile", nil);
    }else if (section == 1){
        headerLabel.text = NSLocalizedString(@"Weight & Measurement", nil);
    }else if (section == 2){
        headerLabel.text = NSLocalizedString(@"Goals", nil);
    }else if (section == 3){
        headerLabel.text = NSLocalizedString(@"More", nil);
    }
    //将自定义的内容添加到UIView上
    [customView addSubview:headerLabel];
    //返回自定义好的效果
    return customView;
}
//别忘了设置高度
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35.0;
}

- (NSString*)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
  return @" ";
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
  //return _nRecdCound;
  if(section == 0)
    return 4;
  else if(section == 1)
    return 4;
  else if(section == 2)
    return 7;
  else
    return 5;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    //self.lineCtrler.hRate = [self.nWgtArray objectAtIndex:indexPath.row];
    //[self.navigationController pushViewController:self.lineCtrler animated:YES];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Touch:", nil) message:NSLocalizedString(@"Test click out row", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
    [alertView show];
  
  /*AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString *titileString = [NSString stringWithFormat:@"你点击了按钮%@", @"tt"];
  [pApp showAlertBox:@"提示" msg:titileString];*/

    //[alertView release];
}

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  NSString *kCellIdentifier =  NSLocalizedString(@"Profile", nil);
  UITableViewCell *cell = [_tabProf dequeueReusableCellWithIdentifier:kCellIdentifier];
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
  }
  cell.backgroundColor = [UIColor clearColor];
  cell.textLabel.textColor = [UIColor blackColor];
  //cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16.0];
  cell.textLabel.font = [UIFont systemFontOfSize:16.0];
    
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  pApp.goalDelegate = self;
  LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
  if(bodyInfo == nil)
    return cell;
  
  NSUInteger sectionNo = indexPath.section;
  NSInteger nIdx = indexPath.row;
  
  NSString* sRightText = @"";
  if(sectionNo == 0) {
    if(nIdx == 0) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[0]];
      /*UILabel *lblRight = [[UILabel alloc] init]; //定义一个在cell最右边显示的label
      lblRight.textColor = [UIColor grayColor];
      lblRight.text = [NSString stringWithFormat:@"%@ %@", _sBodyInfoValue[0], _sBodyInfoValue[1]];
      [cell.contentView addSubview:lblRight];*/
      
      sRightText = [NSString stringWithFormat:@"%@ %@", _sBodyInfoValue[0], _sBodyInfoValue[1]];
    }
    else if(nIdx == 1) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[2]];
      sRightText = _sBodyInfoValue[2];
    }
    else if(nIdx == 2) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[4]];
      sRightText = _sBodyInfoValue[4];
    }
    else {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[5]];
      sRightText = _sBodyInfoValue[5];
    }
    
    //UIImageView* ivLeftArrow  = [self getRightImgView:indexPath.row vctrl:pVCtrl];
    //if(ivLeftArrow != nil)
      //cell.accessoryView = ivLeftArrow;

  }
  else if(sectionNo == 1) {
    if(nIdx == 0) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[6]];
      sRightText = _sBodyInfoValue[6];
    }
    else if(nIdx == 1) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[7]];
      sRightText = _sBodyInfoValue[7];
    }
    else if(nIdx == 2) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[13]];
       sRightText = _sBodyInfoValue[13];
    }
    else {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[14]];
       sRightText = _sBodyInfoValue[14];
    }
  }
  else if(sectionNo == 2) {
    if(nIdx == 0) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@ ", _sBodyInfoTitle[8]];
      sRightText = _sBodyInfoValue[8];
    }
    else if(nIdx == 1) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@ ", _sBodyInfoTitle[9]];
      sRightText = _sBodyInfoValue[9];
    }
    else if(nIdx == 2) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[10]];
      sRightText = _sBodyInfoValue[10];
    }
    else if(nIdx == 3) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[11]];
      sRightText = _sBodyInfoValue[11];
    }
    else if(nIdx == 4) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[12]];
      sRightText = _sBodyInfoValue[12];
    }
    else if(nIdx == 5) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[15]];
      sRightText = _sBodyInfoValue[15];
    }
    else {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[16]];
      sRightText = _sBodyInfoValue[16];
    }
  }
  else {
    if(nIdx == 0) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[17]];
      sRightText = _sBodyInfoValue[17];
    }
    else if(nIdx == 1) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[18]];
      sRightText = _sBodyInfoValue[18];
    }
    else if(nIdx == 2) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[19]];
      sRightText = _sBodyInfoValue[19];
    }
    else if(nIdx == 3) {
      cell.textLabel.text = [NSString stringWithFormat:@"%@", _sBodyInfoTitle[20]];
      sRightText = _sBodyInfoValue[20];
    }
    else {
      cell.textLabel.text = [NSString stringWithFormat:@"%@\t\t\t", NSLocalizedString(@"Version", nil)];
      sRightText = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];;
    }
  }

  cell.detailTextLabel.text = sRightText;
    cell.textLabel.font = Bold(14);
    cell.detailTextLabel.font = Regular(14);
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  //cell.textLabel.textAlignment = NSA
  return cell;
}

//debug
/*- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    H_RateItem* pItem = [_pHrateItem objectAtIndex:indexPath.row];
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSString *kCellIdentifier =  @"Profile";
    UITableViewCell *cell = [_tabProf dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16.0];
    
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    [pApp.dtFmt setDateFormat:@"HH:mm:ss:SSS"];
    cell.textLabel.text =[NSString stringWithFormat:@"%i, %@", pItem.hRateValue.shortValue, [pApp.dtFmt stringFromDate:pItem.hRateTime]];
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];
    return cell;
}*/
//debug

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    if (indexPath.section < 3) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if ([cell.textLabel.text isEqualToString:@"Email"]) {
            AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            NSString *titileString = @"不可修改";
            [pApp showAlertBox:@"提示" msg:titileString];
            return;
        }
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@""
                                                                                  message: cell.textLabel.text
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.text = cell.detailTextLabel.text;
            textField.textColor = [UIColor grayColor];
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        }];
        
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSArray * textfields = alertController.textFields;
            UITextField *textField = [textfields firstObject];
            
            NSLog(@"%@",textField.text);
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        
          AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
          NSString *titileString = @"不可修改";
          [pApp showAlertBox:@"提示" msg:titileString];
    }
    

   
  
  /*NSInteger nIdx = indexPath.item;
  if(nIdx == 3 && !_txtEditBox.enabled)
    return;
  
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  BOOL bIpad = frame.size.height > 1000;
  BOOL bIp6p =  W  >= 414;
  BOOL bIp6 = NO;
  if(!bIp6p)
    bIp6 =  W  > 320;
  BOOL bSmallScr = W == 320;
  //tableView.editing = YES;
  
  CGFloat xPos = bIpad?168: bIp6p?150: bIp6? 142: 125;
  if(nIdx == 12)
    xPos += 12;
  CGFloat xMilePos = 0;
  UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  if (cell != nil) {
    cell.textLabel.text = [NSString stringWithFormat:@"%@:", _sBodyInfoTitle[nIdx]];
    cell.textLabel.textColor = [UIColor orangeColor];
    if(_nUpdIdx >= 0 && _nUpdIdx < _nRecdCound && nIdx != _nUpdIdx) {
      if(nIdx == 5 || nIdx == 8) {
        if([_txtEditBox isDescendantOfView:_tabProf]) {
          [_txtEditBox removeFromSuperview];
        }
      }
      
      NSInteger nIdx = _nUpdIdx;
      cell = [tableView cellForRowAtIndexPath:_lastIdxPath];
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
      
      if(nIdx == 4)
        cell.textLabel.text = [NSString stringWithFormat:@"%@: %@  (%iY)", _sBodyInfoTitle[nIdx], _sBodyInfoValue[nIdx], bodyInfo.nYearAge];
      else if(nIdx == 11)
        cell.textLabel.text = [NSString stringWithFormat:@"%@: %@ %@", _sBodyInfoTitle[nIdx], _sBodyInfoValue[nIdx], [AppDelegate isLanguageChines]? @"Km": @"Miles"];
      else
        cell.textLabel.text = [NSString stringWithFormat:@"%@: %@", _sBodyInfoTitle[nIdx], _sBodyInfoValue[nIdx]];
    
      if([_scCtrlBox isDescendantOfView:_tabProf]) {
        [_scCtrlBox removeFromSuperview];
      }
      if([_txtHgtIn isDescendantOfView:_tabProf]) {
        [_txtHgtIn removeFromSuperview];
      }
      //cell.textLabel.textColor = [UIColor whiteColor];
    }
  }
  
  CGFloat fWid = 120.0;
  
  if(nIdx == 5 || nIdx == 8 || nIdx == _nRecdCound-1) {
    NSInteger nCurtIdx = 0;
     AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [_scCtrlBox removeAllSegments];
    if(nIdx == 5) {
      [_scCtrlBox insertSegmentWithTitle:@"Female" atIndex:0 animated:NO];
      [_scCtrlBox insertSegmentWithTitle:@"Male" atIndex:1 animated:NO];
      _scCtrlBox.frame = CGRectMake(xPos, nIdx * _fRowHgt + 5, 120, _fRowHgt-10);
      
      nCurtIdx = pApp.m_bodyInfo.nGender;
      if(nCurtIdx != 1)
        nCurtIdx = 0;
    }
    else if(nIdx == 8) {
      [_scCtrlBox insertSegmentWithTitle:@"One" atIndex:0 animated:NO];
      [_scCtrlBox insertSegmentWithTitle:@"Two" atIndex:1 animated:NO];
      [_scCtrlBox insertSegmentWithTitle:@"Three" atIndex:2 animated:NO];
      
      _scCtrlBox.frame = CGRectMake(xPos, nIdx * _fRowHgt + 5, 120, _fRowHgt-10);
      nCurtIdx = pApp.m_bodyInfo.nActLvl;
    }
    else if(nIdx == _nRecdCound-1){
      [_scCtrlBox insertSegmentWithTitle:@"USA" atIndex:0 animated:NO];
      [_scCtrlBox insertSegmentWithTitle:@"中国南京" atIndex:1 animated:NO];
      
      _scCtrlBox.frame = CGRectMake(xPos, nIdx * _fRowHgt + 5, 120, _fRowHgt-10);
      nCurtIdx = pApp.m_bodyInfo.nSvrIpIdx;
    }
    [tableView addSubview:_scCtrlBox];
   
    _scCtrlBox.selectedSegmentIndex = nCurtIdx;
  }
  else if(nIdx == 7) {
    NSString* sHgtVal = _sBodyInfoValue[nIdx];
    NSString* sHgtIn = @"";
    
    BOOL bHgtFtUn = [sHgtVal hasSuffix:@"in"];
    fWid = bHgtFtUn?20.0:53.0;
    
    _txtEditBox.frame = CGRectMake(xPos, nIdx * _fRowHgt + 5, fWid, _fRowHgt-10);
    if(bHgtFtUn) {
      sHgtIn = [sHgtVal substringWithRange:NSMakeRange(4, sHgtVal.length-6)];
      sHgtVal = [sHgtVal substringWithRange: NSMakeRange(0, 1)];
    }
    else {
      sHgtVal = [sHgtVal substringWithRange: NSMakeRange(0, sHgtVal.length-3)];
    }
    _txtEditBox.text = sHgtVal;
    [tableView addSubview:_txtEditBox];
    
    [_scCtrlBox removeAllSegments];
    [_scCtrlBox insertSegmentWithTitle:@"cm" atIndex:0 animated:NO];
    [_scCtrlBox insertSegmentWithTitle:@"ft" atIndex:1 animated:NO];
    _scCtrlBox.selectedSegmentIndex = bHgtFtUn?1:0;
    _scCtrlBox.frame = CGRectMake(xPos+fWid+4, nIdx * _fRowHgt + 5, 60, _fRowHgt-10);
    
    //[_scCtrlBox addTarget:self action:@selector(onUnitChged:) forControlEvents:UIControlEventValueChanged];
    [tableView addSubview:_scCtrlBox];
    
    //if(bHgtFtUn) {
      _txtHgtIn.frame = CGRectMake(xPos+90, nIdx * _fRowHgt + 5, 20, _fRowHgt-10);
      _txtHgtIn.text = sHgtIn;
      [tableView addSubview:_txtHgtIn];
  
      _lblUnit.text = @"in";
      _lblUnit.frame = CGRectMake(xPos+111, nIdx * _fRowHgt + 5, 60, _fRowHgt-10);
      [tableView addSubview:_lblUnit];
      
      _txtHgtIn.hidden = !bHgtFtUn;
      _lblUnit.hidden = !bHgtFtUn;
    //}
  }
  else if(nIdx == 11) {
    fWid = 53.0;
    _txtEditBox.frame = CGRectMake(xPos, nIdx * _fRowHgt + 5, fWid, _fRowHgt-10);
    _txtEditBox.text = _sBodyInfoValue[nIdx];
    [tableView addSubview:_txtEditBox];
  }
  else {
    if(nIdx == 6 || nIdx == 9 || nIdx == 11 || nIdx == 12)
      fWid = 54.0;
    else if(nIdx == 13 || nIdx == 14)
      fWid = 40;
    else if(nIdx == 15)
      fWid = 80.0;
    else if(nIdx == 16)
      fWid = 60;
    else
       fWid = 100;
    _txtEditBox.frame = CGRectMake(xPos, nIdx * _fRowHgt + 5, fWid, _fRowHgt-10);
    _txtEditBox.text = _sBodyInfoValue[nIdx];
    [tableView addSubview:_txtEditBox];
    
    if(nIdx == 6 || nIdx == 9 || nIdx == 13 || nIdx == 14) {
      [_scCtrlBox removeAllSegments];
      if(nIdx == 6 || nIdx == 9) {
        NSString* sWgt =  _txtEditBox.text;
        sWgt = [sWgt substringWithRange: NSMakeRange(0, sWgt.length-3)];
        _txtEditBox.text = sWgt;
        
        [_scCtrlBox insertSegmentWithTitle:@"kg" atIndex:0 animated:NO];
        [_scCtrlBox insertSegmentWithTitle:@"kg" atIndex:1 animated:NO];
      }
      else {
        NSString* sLen = _txtEditBox.text;
        if(sLen.length > 0) {
          sLen = [sLen substringWithRange: NSMakeRange(0, sLen.length-3)];
        }
        _txtEditBox.text = sLen;
        [_scCtrlBox insertSegmentWithTitle:@"cm" atIndex:0 animated:NO];
        [_scCtrlBox insertSegmentWithTitle:@"in" atIndex:1 animated:NO];
      }
      _scCtrlBox.frame = CGRectMake(xPos+fWid+((nIdx == 13 || nIdx == 14)?4:8), nIdx * _fRowHgt + 5, 60, _fRowHgt-10);
      [tableView addSubview:_scCtrlBox];
      
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      if(nIdx == 6 || nIdx == 9)
        _scCtrlBox.selectedSegmentIndex = pApp.m_bodyInfo.nWgtUn - 1;
      else
        _scCtrlBox.selectedSegmentIndex = pApp.m_bodyInfo.nHgtUn - 1;
    }
  }
  
  xMilePos = xPos+fWid+8;
  _txtEditBox.hidden = NO;
  //[self dismissViewControllerAnimated:YES completion:nil];
  //xPos += (nIdx < 12)?128:116 + (bIp6?15:0);
  if(bSmallScr)
    xPos += (nIdx < 12)?128:120;
  else
    xPos = W - _fRowHgt * (bIpad? 14.0: 2.75);
  _btnUpdate.frame = CGRectMake(xPos, nIdx * _fRowHgt + 1, _fRowHgt-4, _fRowHgt-4);
  [tableView addSubview:_btnUpdate];
  
  //xPos += _fRowHgt + (bIp6?15:1);

  if(bSmallScr)
     xPos += _fRowHgt * 1.1 + 4;
  else
    xPos += _fRowHgt * (bIpad? 2.5: 1.50);
  _btnCancel.frame = CGRectMake(xPos, nIdx * _fRowHgt + 3, _fRowHgt-4, _fRowHgt-4);
  [tableView addSubview:_btnCancel];
  //NSString* sMsg = [NSString stringWithFormat:@"sel row: %i", (int)indexPath.item];
  //[_btnClearData setTitle:sMsg forState:UIControlStateNormal];
  
  if((!bIpad && nIdx > 5) || nIdx == _nRecdCound-1) {
    CGPoint pt = _tabProfPos;
    pt.y -= (nIdx-5) * (_fRowHgt);
    _tabProf.center = pt;
  }
  else {
     _tabProf.center = _tabProfPos;
  }
  
  if(nIdx >= 11 && nIdx <= 12) { //step distance, mile unit
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    short nMaxHrt = [pApp calHrateFitnessRng:NO];
    //_lblUnit.text = (nIdx==11)?([AppDelegate isLanguageChines]? @"Km":@"Miles"):[NSString stringWithFormat:@"R:%i", nMaxHrt];
    _lblUnit.text = (nIdx==11)?((pApp.m_bodyInfo.nHgtUn==1)? @"Km":@"Miles"):[NSString stringWithFormat:@"R:%i", nMaxHrt];
    _lblUnit.frame = CGRectMake(xMilePos, nIdx * _fRowHgt + 5, 60, _fRowHgt-10);
    [tableView addSubview:_lblUnit];
  }
  if(_scCtrlBox != nil) {
    if(nIdx == 6 || nIdx == 7) {
      [_scCtrlBox addTarget:self action:@selector(onUnitChged:) forControlEvents:UIControlEventValueChanged];
    }
  }
  _scCtrlBox.enabled = nIdx >= 5 && nIdx <= 8;
  _txtEditBox.enabled = nIdx != 3;
  
  _nUpdIdx = (short)nIdx;
  _lastIdxPath = indexPath;
  
  if(nIdx == 3) {
    _btnUpdate.hidden = YES;
    [self setTagIdTimer];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please scan Tag Id on Scale DBFS221 at first."
                          message:nil delegate:self cancelButtonTitle:nil
                          otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
    [alert show];
    //AudioServicesPlaySystemSound(1109);
  }
  else {
    _btnUpdate.hidden = NO;
    //[_txtEditBox becomeFirstResponder];
    if(_tagIdTimer != nil) {
      [_tagIdTimer invalidate];
      _tagIdTimer = nil;
    }
  }*/
}

- (void) setTagIdTimer
{
  if(_tagIdTimer != nil)
    return;
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sBodyId = [NSString stringWithFormat:@"%ld", (long)pApp.m_bodyInfo.m_nBodyId];
  
  NSString* sUrl = @"Mfw";
  NSDictionary *measInfo = @{
                             @"_nBodyId" : [NSString stringWithFormat:@"%@", sBodyId],
                             @"_sTagId" : @"???",
                             @"_nType" : @"2"
                             };
  
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:sUrl data:measInfo];
  //request.timeoutInterval = 10.0;
  [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  
  _tagIdTimer = [NSTimer scheduledTimerWithTimeInterval:2.50 target:self selector:@selector(onTagIdRecvTimer:) userInfo:sBodyId repeats:YES];
}

-(void) onTagIdRecvTimer:(NSTimer*)sBodyId
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* _sBodyId = (NSString*)[sBodyId userInfo];

  NSString* sUrl = [NSString stringWithFormat:@"Mfw/GetUpdateTagId/%@", _sBodyId];
 
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"Get" url:sUrl data:nil];
  //request.timeoutInterval = 10.0;
  
  NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  if (data != nil) {
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if(![sRecv isEqualToString:@"null"] && ![sRecv containsString:@"???"]) {
      sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
      NSArray *listItems = [sRecv componentsSeparatedByString:@":"];
      if(sRecv != nil && listItems.count > 1) {
        _txtEditBox.text = listItems[0];
        _sDevId = listItems[1];
        _btnUpdate.hidden = NO;
        
        [_tagIdTimer invalidate];
        _tagIdTimer = nil;
        AudioServicesPlaySystemSound(1109);
      }
    }
  }
}



- (void) onUnitChged:sender
{
  if(_nUpdIdx != 6 && _nUpdIdx != 7)
    return;
  
  if(_nUpdIdx == 6) {
    CGFloat fWgt = _txtEditBox.text.floatValue;
    BOOL bLbUnit = _scCtrlBox.selectedSegmentIndex == 1;
    if(bLbUnit) {
      fWgt *= _KgtoLb;
    }
    else {
      fWgt *= _LbtoKg;
    }
    _txtEditBox.text = [NSString stringWithFormat:@"%.1f", fWgt];
    return;
  }
  CGRect rt = _txtEditBox.frame;
  CGPoint pt = _scCtrlBox.center;
  CGFloat fDelta = 0.0;
  BOOL bHgtFt = _scCtrlBox.selectedSegmentIndex == 1;
  CGFloat fHgtVal = _txtEditBox.text.floatValue;
  if(bHgtFt) {
    fHgtVal /= 100.0;
    fHgtVal /= _FtToMeter ; 
    rt.size.width = 20.0;
    fDelta = rt.size.width - 53;
  }
  else {
    fHgtVal += _txtHgtIn.text.floatValue / 12.0;
    fHgtVal *= (_FtToMeter * 100);
    rt.size.width = 53.0;
    fDelta = rt.size.width - 20;
  }
  _txtEditBox.frame = rt;
  if(bHgtFt) {
    _txtEditBox.text = [NSString stringWithFormat:@"%i", (short)fHgtVal];
    _txtHgtIn.text = [NSString stringWithFormat:@"%.0f", (fHgtVal - (short)fHgtVal) * 12.0];
  }
  else {
    _txtEditBox.text = [NSString stringWithFormat:@"%.1f", fHgtVal];
  }
  pt.x += fDelta;
  _scCtrlBox.center = pt;
  
  _txtHgtIn.hidden = !bHgtFt;
  _lblUnit.hidden = !bHgtFt;
}

- (void) tapImgBtnView:sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(sender == _btnUpdate) {
    NSString* sInfo = _txtEditBox.text;
    
    if(_nUpdIdx == 0) {
      sInfo = [sInfo stringByAppendingFormat:@" %@", _sBodyInfoValue[1]];
      short nUnit = _nUpdIdx + 1;
      [pApp updBodyRegInfo:_nUpdIdx info:sInfo unit:nUnit];
    }
    else if(_nUpdIdx == 1) {
      sInfo = [NSString stringWithFormat:@"%@ %@", _sBodyInfoValue[0], _txtEditBox.text];
      short nUnit = _nUpdIdx + 1;
      [pApp updBodyRegInfo:_nUpdIdx info:sInfo unit:nUnit];
    }
    else if(_nUpdIdx == 3) {
      NSString* sTagId = _txtEditBox.text;
      NSString* sDevId = _sDevId;
      [pApp updTagIdDevTimeZone: sTagId devId:sDevId];
      //return;
    }
    else if(_nUpdIdx == 4) {
      NSDate* dtBorn = [pApp.m_bodyInfo.dtFmt dateFromString:sInfo];
      if(dtBorn == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Date Format" message:@"Date Format is not right!" delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
        [alertView show];
        return;
      }
      
      
      if([AppDelegate isLanguageChines]) {
        NSArray *listItems = [sInfo componentsSeparatedByString:@"-"];
        if(listItems.count <= 1)
          return;
        
        sInfo = listItems[0];
        sInfo = [sInfo stringByAppendingFormat:@"-%@-01", listItems[1]];
      }
      else {
        NSArray *listItems = [sInfo componentsSeparatedByString:@"/"];
        if(listItems.count <= 1)
          return;
        
        sInfo = listItems[0];
        sInfo = [sInfo stringByAppendingFormat:@"/01/%@", listItems[1]];
      }
      
      
      short nUnit = _nUpdIdx + 1;
      [pApp updBodyRegInfo:_nUpdIdx info:sInfo unit:nUnit];
    }
    
    else if(_nUpdIdx == 5 ) {
      short nSex = _scCtrlBox.selectedSegmentIndex;
      [pApp updBodyRegGender:nSex];
    }
    else if(_nUpdIdx == 7) {
      BOOL bHgtFt = _scCtrlBox.selectedSegmentIndex == 1;
      CGFloat fHgtVal = sInfo.floatValue;
      if(bHgtFt)
        fHgtVal += (_txtHgtIn.text.floatValue + 0.001) / 12.0;
      else
        fHgtVal /= 100.0;
        
      [pApp updBodyRegHgt:fHgtVal bFtUnit:bHgtFt];

    }
    else if(_nUpdIdx == 8) {
      short nAct = _scCtrlBox.selectedSegmentIndex;
      [pApp updBodyRegActLvl:nAct];
    }
    else if(_nUpdIdx == _nRecdCound-1) {
      short nSvrIdx = _scCtrlBox.selectedSegmentIndex;
      [pApp updSvrIpAddress:nSvrIdx];
    }
    else {
      short nUnit = _scCtrlBox.selectedSegmentIndex + 1;
      if(_nUpdIdx == 11)
        nUnit = [AppDelegate isLanguageChines]?1:2;
      else if(_nUpdIdx == 10 || _nUpdIdx == 12)
        nUnit = 0;
      
      if(_nUpdIdx == 12) {
        [pApp updMaxBpmVal:sInfo unit:nUnit view:self];
      }
      else {
        [pApp updBodyRegInfo:_nUpdIdx info:sInfo unit:nUnit];
      }
        
    }
    [self setBodyInfo];
    //[_btnClearData setTitle:@"Update" forState:UIControlStateNormal];
  }
  else {
    //[_btnClearData setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
    if(_tagIdTimer != nil) {
      [_tagIdTimer invalidate];
      _tagIdTimer = nil;
    }
  }
  
  if([_txtEditBox isDescendantOfView:_tabProf]) {
    [_txtEditBox removeFromSuperview];
  }
  if([_scCtrlBox isDescendantOfView:_tabProf]) {
    [_scCtrlBox removeFromSuperview];
  }
  if([_txtHgtIn isDescendantOfView:_tabProf]) {
    [_txtHgtIn removeFromSuperview];
  }
  if([_lblUnit isDescendantOfView:_tabProf]) {
    [_lblUnit removeFromSuperview];
  }
  
  [_btnUpdate removeFromSuperview];
  [_btnCancel removeFromSuperview];
  _tabProf.center = _tabProfPos;
  [_tabProf reloadData];
  _nUpdIdx = -1;
  _txtEditBox.enabled = YES;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
  if(_nUpdIdx >= 0) {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor whiteColor];
    if(_nUpdIdx == 7)
      _lblUnit.hidden = YES;
  }
}

//-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//  NSString *titileString = [NSString stringWithFormat:@"你点击了: %ld/%ld", (long)indexPath.row, (long)indexPath.section];
//  [pApp showAlertBox:@"提示" msg:titileString];
//  return indexPath;
//  
//  
//  /*NSUInteger nRow = [indexPath row];
//  //if (nRow == 3 || nRow == 8) {
//  if ((nRow == 2 || nRow >= 17)) {
//    AudioServicesPlaySystemSound(1112);
//    return nil;
//  }
//  
//  
//  if(_scCtrlBox != nil)
//    [_scCtrlBox removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
//  return indexPath;*/
//}



- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
  [_btnClearData setTitle:@"Edit Action" forState:UIControlStateNormal];
  return nil;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Detemine if it's in editing mode
    if (self.editing) {
        return UITableViewCellEditingStyleDelete;
    }
    
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tabView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 [_btnClearData setTitle:@"Edit Data" forState:UIControlStateNormal];
  /*if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Ensure that if the user is editing a name field then the change is committed before deleting a row -- this ensures that changes are made to the correct event object.
      [_toupper(<#c#>) endEditing:YES];
        
      AppDelegate *pApp= [[UIApplication sharedApplication] delegate];
        
      NSManagedObjectContext* managedObjectContext = pApp.managedObjectContext;
        
        // Delete the managed object at the given index path.
        NSManagedObject *rcdToDelete = [m_nWgtArray objectAtIndex:indexPath.row];
        [managedObjectContext deleteObject:rcdToDelete];
        
        // Update the array and table view.
        [m_nWgtArray removeObjectAtIndex:indexPath.row];
        [_tabView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        // Commit the change.
        NSError *error;
        if (![managedObjectContext save:&error]) {
            // Handle the error.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            exit(-1);  // Fail
        }
        else {
            [_tabView reloadData];
        }
        
        //[self performSelector:@selector(updateRowTags) withObject:nil afterDelay:0.0];
    }*/
}

- (void) onUserLogout:(id)sender
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  pApp.m_nLastHrate = 0;
  pApp.m_nCurtAvgHrt = 0;
  
  if(sender == _btnLogout) {
    [pApp userLogout];
  }
  else {
    [pApp clearStoreData];
  }
}

- (void) updateGoalData
{
  [self setBodyInfo];
  [_tabProf reloadData];
}

- (void) showAppVerInfo:(NSString*)sMsg
{
  _lblAppVer.text = sMsg;
}

@end
